/*
 *  Copyright 2015 Google Inc. All Rights Reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.google.blockly.ohos;

import com.google.blockly.model.Workspace;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.service.DisplayManager;

import java.io.InputStream;

/**
 * ability holding a full-screen Blockly workspace with multiple sections in the navigation menu.
 */
public abstract class BlocklySectionsAbility extends AbstractBlocklyAbility
        implements ListContainer.ItemClickedListener {
    private static final String TAG = "BlocklySectionsAbility";

    protected int mCurrentSection = 0;
    protected ListContainer mSectionsListView;
    protected BaseItemProvider mListAdapter;
    protected PopupDialog mSectionsDialog;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        Image imgSections = (Image) findComponentById(ResourceTable.Id_action_sections);
        imgSections.setVisibility(Component.VISIBLE);
        imgSections.setClickedListener(component -> showSectionsDialog());
        mSectionsListView = (ListContainer) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_sections_list, null, false);
        mListAdapter = onCreateSectionsListAdapter();
        mSectionsListView.setItemProvider(mListAdapter);
        mSectionsListView.setItemClickedListener(this);
    }

    private void showSectionsDialog() {
        if (mSectionsDialog == null) {
            mSectionsDialog = new PopupDialog(this, findComponentById(ResourceTable.Id_action_root));
            mSectionsDialog.setCustomComponent(mSectionsListView);
            mSectionsDialog.setSize(
                    DisplayManager.getInstance().getDefaultDisplay(getContext()).get().getAttributes().width / 2,
                    findComponentById(ResourceTable.Id_work_root).getHeight());
            mSectionsDialog.setDialogListener(() -> {
                mSectionsDialog.hide();
                return false;
            });
        }
        if (!mSectionsDialog.isShowing()) {
            mSectionsDialog.show();
        }
    }

    @Override
    public void onItemClicked(ListContainer listContainer, Component component, int position, long id) {
        onSectionItemClicked(position);
    }

    /**
     * Handles the selection of a section, including closing the navigation drawer.
     *
     * @param sectionIndex
     */
    public void onSectionItemClicked(int sectionIndex) {
        mSectionsDialog.hide();
        if (mCurrentSection == sectionIndex) {
            return;
        }
        changeSection(sectionIndex);
        mListAdapter.notifyDataChanged();
    }

    /**
     * @return The title of the current workspace / section.
     */

    protected CharSequence getWorkspaceTitle() {
        int section = getCurrentSectionIndex();
        if (section < getSectionCount()) {
            return (String) mListAdapter.getItem(section);
        } else {
            // Use the ability name.
            //return getTitle();
            return "";
        }
    }

    /**
     * Populate the navigation menu with the list of available sections.
     *
     * @return An adapter of sections for the navigation menu.
     */

    abstract protected BaseItemProvider onCreateSectionsListAdapter();

    /**
     * @return The section that is currently displayed.
     */
    public final int getCurrentSectionIndex() {
        return mCurrentSection;
    }

    /**
     * Called to load a new Section. If you don't want to re-use the previous section's
     * code {@link Workspace#loadWorkspaceContents(InputStream)} should be called here.
     *
     * @param oldSection The previous level.
     * @param newSection The level that was just configured.
     * @return True if the new section was successfully loaded. Otherwise false.
     */
    abstract protected boolean onSectionChanged(int oldSection, int newSection);

    /**
     * @return The number of sections in this ability.
     */
    protected int getSectionCount() {
        return mListAdapter.getCount();
    }

    private void changeSection(int level) {
        int oldLevel = mCurrentSection;
        mCurrentSection = level;
        if (onSectionChanged(oldLevel, level)) {
            resetBlockFactory();
            reloadToolbox();
        } else {
            mCurrentSection = oldLevel;
        }
    }
}
